package gamecfg

import (
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/glog"
	"time"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/xrjson"
)

var activityMap = make(map[uint64]*ActivityCfg)

// ActivityCfg 活动配置结构体
type ActivityCfg struct {
	Id        uint64 `json:"id"`
	StartTime string `json:"startTime"`
	EndTime   string `json:"endTime"`
	Broadcast bool   `json:"broadcast"`
	Name      string `json:"name"`
	Pub       bool   `json:"pub"`
	Type      int    `json:"type"`
}

// loadActivityCfg 加载活动配置
func loadActivityCfg(jsonStr string) {
	err := json.Unmarshal([]byte(jsonStr), &activityMap)
	if err != nil {
		panic(fmt.Errorf("%v 文件加载错误 %v", jsonStr, err))
	}
	glog.Warningf(gctx.New(), "%s数据加载成功,长度:%v", jsonStr, len(activityMap))
}

// GetActivityCfgById 根据ID获取活动配置
func GetActivityCfgById(id uint64) *ActivityCfg {
	val, ok := activityMap[id]
	if ok {
		return val
	}
	return nil
}

// GetAllActivityCfg 获取所有活动配置
func GetAllActivityCfg() []*ActivityCfg {
	ret := make([]*ActivityCfg, common.Zero)
	for _, v := range activityMap {
		ret = append(ret, v)
	}
	return ret
}

// GetStartTime 获取活动开始时间
func (a *ActivityCfg) GetStartTime() time.Time {
	t, err := time.ParseInLocation("2006-01-02 15:04:05", a.StartTime, time.Local)
	if err != nil {
		return time.Time{}
	}
	return t
}

// GetEndTime 获取活动结束时间
func (a *ActivityCfg) GetEndTime() time.Time {
	t, err := time.ParseInLocation("2006-01-02 15:04:05", a.EndTime, time.Local)
	if err != nil {
		return time.Time{}
	}
	return t
}

// IsActivityActive 判断活动是否正在进行中
func (a *ActivityCfg) IsActivityActive() bool {
	now := time.Now()
	startTime := a.GetStartTime()
	endTime := a.GetEndTime()

	return !startTime.IsZero() && !endTime.IsZero() &&
		now.After(startTime) && now.Before(endTime) && a.Pub
}

// initActivity 初始化活动配置
func initActivity() {
	xrjson.RegLoadJsonHandler("activity.json", loadActivityCfg)
}
